<!DOCTYPE HTML>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>图书管理</title>
    <script id="header" type="text/javascript"
            src="../js/header.js?head=../"></script>
    <script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/localization/messages_zh.js"></script>
</head>
<body>
<nav class="breadcrumb">
    <i class="Hui-iconfont">&#xe67f;</i> 首页 <span class="c-gray en">&gt;</span>
    图书管理 <a class="btn btn-success radius r mr-20"
            style="line-height: 1.6em; margin-top: 3px"
            href="javascript:location.replace(location.href);" title="刷新"><i
                class="Hui-iconfont">&#xe68f;</i></a>
</nav>
<div class="pd-20">
    <div class="">
        <table class="searchTable" >
            <tr>
                <td>
                    <span class="f-18 "><strong>查询：</strong> </span>
                    <input type="text" id="searchBookNameAndIsbn" onkeyup="catchName(this.value)"  style="width: 250px;" class="input-text box-shadow" placeholder="请输入查询内容">
                    &nbsp;&nbsp;&nbsp;
                    <select class="input-text box-shadow" style="width: 70px;" id="searchBookFormat">
                        <option value="">开数</option>
                        <option value="8开">8开</option>
                        <option value="16开">16开</option>
                        <option value="24开">24开</option>
                        <option value="28开">28开</option>
                        <option value="32开">32开</option>
                        <option value="36开">36开</option>
                        <option value="42开">42开</option>
                        <option value="64开">64开</option>
                    </select>
                    &nbsp;&nbsp;&nbsp;&nbsp;
                    <select class="input-text box-shadow" style="width: 70px;" id="searchBookFraming">
                        <option value="" >装帧</option>
                        <option value="精装" >精装</option>
                        <option value="平装" >平装</option>
                    </select>
                    <div class="pos-a  box-shadow" style="margin-left:37px;pointer-events: none">
                        <lableList  style="width: 340px;background-color: white;display: none" class="bookNameList pd-10" id="bookNameList"></lableList>

                    </div>

                    &nbsp;&nbsp;&nbsp;<button class="btn btn-primary radius box-shadow" onclick="searchData()">查询</button>
                </td>

            </tr>
        </table>
    </div>
    <div class="cl pd-5 bg-1 bk-gray">
			<span class="l"> <a href="javascript:;"
                                onclick="javascript:add();" id="saveData"
                                class="btn btn-primary radius"><i class="Hui-iconfont">&#xe600;</i>新增</a>
				<a href="javascript:;" onclick="bathDelete();" id="deleteData"
                   class="btn btn-danger radius"><i class="Hui-iconfont">&#xe6e2;</i>
					批量删除</a>
			</span>
    </div>
    <div class="mt-20">
        <table class="table table-border table-bordered table-hover table-bg table-sort table-striped" id="main">
            <thead>
            <tr class="text-c">
                <th width="25"><input type="checkbox" name="" value=""></th>
                <th width="50">id</th>
                <th width="100">图书名称</th>
                <th width="100">图书封面</th>
                <th width="100">作者</th>
                <th width="100">出版社</th>
                <th width="100">出版日期</th>
                <th width="100">定价</th>
                <th width="100">装帧</th>
                <th width="100">开本</th>
                <th width="100">ISBN</th>
                <th width="100">热销指数</th>
                <th width="100">创建时间</th>
                <th width="80">创建者</th>
                <th width="100">更新时间</th>
                <th width="80">更新者</th>
                <th width="140">操作</th>
            </tr>
            </thead>
        </table>
    </div>
</div>

<div id="formShow" class="pd-20 hui-fadein " style="display: none;">
    <form action="" method="post" class="form form-horizontal"
          id="submitForm">
        <div class="row cl">
            <input id="id" name="id" style="display: none;" /> <input
                    id="dataType" name="dataType" style="display: none;" /> <label
                    class="form-label col-xs-2 col-sm-2 " for="name"><span class="c-red">*</span>图书名称：</label>
            <div class="formControls col-xs-4 col-sm-4">
                <input type="text" class="input-text required" onchange="checkBookNameTel(this.value)" value="" placeholder=""
                       id="name" name="name" >
            </div>
            <label class="form-label col-xs-2 col-sm-2"><span
                        class="c-red"></span>图书封面连接：</label>
            <div class="formControls col-xs-4 col-sm-4">
                <input type="text" class="input-text required url" value="" placeholder=""
                       id="img" name="img">
            </div>
        </div>

        <div class="row cl">
            <input id="id" name="id" style="display: none;" /> <input
                    id="dataType" name="dataType" style="display: none;" /> <label
                    class="form-label col-xs-2 col-sm-2"><span class="c-red">*</span>作者：</label>
            <div class="formControls col-xs-4 col-sm-4">
                <input type="text" class="input-text required" value="" placeholder="" id="authorId" name="authorId">

            </div>
            <label class="form-label col-xs-2 col-sm-2"><span
                        class="c-red">*</span>出版社：</label>
            <div class="formControls col-xs-4 col-sm-4">
                <input type="text" class="input-text required" value="" placeholder=""
                       id="pbhouseId" name="pbhouseId">
            </div>
        </div>
        <div class="row cl">
            <input id="id" name="id" style="display: none;" /> <input
                    id="dataType" name="dataType" style="display: none;" /> <label
                    class="form-label col-xs-2 col-sm-2"><span class="c-red">*</span>出版日期：</label>
            <div class="formControls col-xs-4 col-sm-4">
                <input type="date" class="input-text required" value="" placeholder=""
                       id="date" name="date">
            </div>
            <label class="form-label col-xs-2 col-sm-2"><span
                        class="c-red">*</span>定价(￥)：</label>
            <div class="formControls col-xs-4 col-sm-4">
                <input type="text" class="input-text required" value="" placeholder=""
                       id="price" name="price">
            </div>
        </div>

        <div class="row cl">
            <input id="id" name="id" style="display: none;" /> <input
                    id="dataType" name="dataType" style="display: none;" /> <label
                    class="form-label col-xs-2 col-sm-2"><span class="c-red">*</span>装帧：</label>
            <div class="formControls col-xs-4 col-sm-4">
                <select class="select valid" size="1" name="framing" id="framing">
                    <option value="精装">精装</option>
                    <option value="平装">平装</option>

                </select>
            </div>
            <label class="form-label col-xs-2 col-sm-2"><span
                        class="c-red">*</span>开本：</label>
            <div class="formControls col-xs-4 col-sm-4">
                <select class="select valid" size="1" name="format" id="format">
                    <option value="8开">8开</option>
                    <option value="16开">16开</option>
                    <option value="24开">24开</option>
                    <option value="28开">28开</option>
                    <option value="32开">32开</option>
                    <option value="36开">36开</option>
                    <option value="42开">42开</option>
                    <option value="64开">64开</option>
                </select>
            </div>
        </div>

        <div class="row cl">
            <input id="id" name="id" style="display: none;" /> <input
                    id="dataType" name="dataType" style="display: none;" /> <label
                    class="form-label col-xs-2 col-sm-2"><span class="c-red">*</span>ISBN：</label>
            <div class="formControls col-xs-4 col-sm-4">
                <input type="text" class="input-text required digits" onchange="checkBookIsbnTel(this.value)" value="" placeholder=""
                       id="isbn" name="isbn">
            </div>
        </div>
        <div class="row cl">
            <div class="col-9 col-offset-3">
                <input class="btn btn-primary radius" id="submit" onclick="submitFrom()" value="提交">
            </div>
        </div>
    </form>
</div>
<script type="text/javascript">
    var base = "../dataBook/";
    var findPage = "findBookByPage";
    var updateBook = "updateBookById";
    var deleteBook = "deleteBookById";
    var findBookByName = "findBookByName";
    var findBookByIsbn = "findBookByIsbn";
    var findBookName = "findBookName";
    var findOne = "findBookOne";
    var addBook = "addBookData";
    var img404 ="https://img2.baidu.com/it/u=2721702834,1752400983&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500"
    var pageUrl = base + findPage;
    var updateBookUrl = base + updateBook;
    var deleteBookUrl = base + deleteBook;
    var editUrl = base + findOne;
    var addUrl = base + addBook;
    var bookNameUrl = base + findBookByName;
    var bookIsbnUrl = base + findBookByIsbn;
    var findBookNameUrl = base + findBookName;
    var pageSize = 7;
    var dataTable;
    $(function() {
        dataTable = MyDataTable({
            id : "main",
            pageUrl : pageUrl,
            param : function() {
                var p={"searchBookNameAndIsbn":$('#searchBookNameAndIsbn').val(),
                    "searchBookFormat":$('#searchBookFormat').val(),
                    "searchBookFraming":$('#searchBookFraming').val()};
                return p;
            },
            "columns" : [
                {
                    "orderable" : false,
                    "className" : 'text-c',
                    "render" : function(data, type, full) {
                        return '<td><input name="" type="checkbox" value="'+full.id+'"></td>';
                    }
                },{
                    "data" : "id",
                    "orderable" : false,
                    "className" : 'text-c',
                    "render" : function(data, type, full) {
                        if (data) {
                            return data;
                        }
                        return "";
                    }
                },

                {
                    "data" : "name",
                    "orderable" : false,
                    "className" : 'text-c',
                    "render" : function(data, type, full) {
                        if (data) {
                            return data;
                        }
                        return "";
                    }
                },
                {
                    "data" : "img",
                    "orderable" : false,
                    "className" : 'text-c',
                    "render" : function(data, type, full) {
                        if (data!=null&&data!=""){
                            return "<img style='width: 100px;height: 100px;' onerror='imgError(this);' src="
                                + data
                                + "/>"
                        }
                        else {
                            return "<img style='width: 100px;height: 100px;' onerror='imgError(this);' src="
                                + img404
                                + "/>"
                        }


                    }
                },
                {
                    "data" : "authorId",
                    "orderable" : false,
                    "className" : 'text-c',
                    "render" : function(data, type, full) {
                        if (data) {
                            return data;
                        }
                        return "";
                    }
                },
                {
                    "data" : "pbhouseId",
                    "orderable" : false,
                    "className" : 'text-c',
                    "render" : function(data, type, full) {
                        if (data) {
                            return data;
                        }
                        return "";
                    }
                },
                {
                    "data" : "date",
                    "orderable" : false,
                    "className" : 'text-c',
                    "render" : function(data, type, full) {
                        if (data) {
                            return data;
                        }
                        return "";
                    }
                },
                {
                    "data" : "price",
                    "orderable" : false,
                    "className" : 'text-c',
                    "render" : function(data, type, full) {
                        if (data) {
                            return data;
                        }
                        return "";
                    }
                },

                {
                    "data" : "framing",
                    "orderable" : false,
                    "className" : 'text-c',
                    "render" : function(data, type, full) {
                        if (data) {
                            return data;
                        }
                        return "";
                    }
                },
                {
                    "data" : "format",
                    "orderable" : false,
                    "className" : 'text-c',
                    "render" : function(data, type, full) {
                        if (data) {
                            return data;
                        }
                        return "";
                    }
                },
                {
                    "data" : "isbn",
                    "orderable" : false,
                    "className" : 'text-c',
                    "render" : function(data, type, full) {
                        if (data) {
                            return data;
                        }
                        return "";
                    }
                },
                {
                    "data" : "hot",
                    "orderable" : false,
                    "className" : 'text-c',
                    "render" : function(data, type, full) {
                        if (data) {
                            return data;
                        }
                        return "";
                    }
                },
                {
                    "data" : "createTime",
                    "orderable" : false,
                    "className" : 'text-c',
                    "render" : function(data, type, full) {
                        if (data) {
                            return data;
                        }
                        return "暂无";
                    }
                },
                {
                    "data" : "createBy",
                    "orderable" : false,
                    "className" : 'text-c',
                    "render" : function(data, type, full) {
                        if (data) {
                            return data;
                        }
                        return "暂无";
                    }
                },
                {
                    "data" : "updateTime",
                    "orderable" : false,
                    "className" : 'text-c',
                    "render" : function(data, type, full) {
                        if (data) {
                            return data;
                        }
                        return "暂无";
                    }
                },
                {
                    "data" : "updateBy",
                    "orderable" : false,
                    "className" : 'text-c',
                    "render" : function(data, type, full) {
                        if (data) {
                            return data;
                        }
                        return "暂无";
                    }
                },
                {
                    "orderable" : false,
                    "className" : 'text-c',
                    "render" : function(data, type, full) {
                        return "<a class="
                            + updateBook
                            + "  title = '修改' onclick='edit(\""
                            + full.id
                            + "\");'><i class='Hui-iconfont'>&#xe6df;</i></a>"
                            + "&#12288;<a  class="
                            + deleteBook
                            + "  title = '删除' onclick='deletePlat(\""
                            + full.id
                            + "\");'><i class='Hui-iconfont'>&#xe6e2;</i></a>";
                    }
                } ]
        });
    });

    myValidate()
    // 自定义规则 图书名
    $.validator.addMethod("verifyName", function(value, element) {
        let tel = /^[\u4e00-\u9fa5/A-Za-z/0-9]{2,20}/;
        return this.optional(element) || (((tel.test(value)) && checkBookName(value)) || nameFl);
    }, "Error. custom rules: verifyName");
    // 自定义规则 价格
    $.validator.addMethod("verifyPrice", function(value, element) {
        let tel = /^[0-9/.]{1,5}$/;
        return this.optional(element) || (tel.test(value));
    }, "Error. custom rules: verifyPrice");
    // 自定义规则 作者id
    $.validator.addMethod("verifyAuthorId", function(value, element) {
        let tel = /^[0-9]{1,10}$/;
        return this.optional(element) || (tel.test(value));
    }, "Error. custom rules: verifyAuthorId");
    // 自定义规则 出版社
    $.validator.addMethod("verifyPbhouseId", function(value, element) {
        let tel = /^[0-9]{1,10}$/;
        return this.optional(element) || (tel.test(value));
    }, "Error. custom rules: verifyPbhouseId");
    // 自定义规则 ISBN码
    $.validator.addMethod("verifyIsbn", function(value, element) {
        let tel = /^[0-9]{13}$/;
        return this.optional(element) || (((tel.test(value)) && checkBookIsbn(value)) || isbnFl);
    }, "Error. custom rules: verifyIsbn");

    //name验证器
    var nameFl = false
    function checkBookNameTel(data){
        nameFl = false
        let telName = /^[\u4e00-\u9fa5/A-Za-z/0-9]{2,20}/;
        let name = $('#name').val()
        if (data.id?true:false){
            nameFl = data===''?nameFl=(name===data.name):nameFl=telName.test(name);
        }
        return nameFl
    }
    //isbn验证器
    var isbnFl = false
    function checkBookIsbnTel(data){
        isbnFl = false
        let telIsbn = /^[0-9]{13}$/;
        let isbn = $('#isbn').val()
        if (data.id?true:false){
            isbnFl = data===''?isbnFl=(isbn===data.isbn):isbnFl=telIsbn.test(isbn);
        }
        return  isbnFl
    }
    //数据库验证
    function checkBookIsbn(isbn){
        var flag = true;
        $.ajax({
            type : "get",
            dataType : "json",
            data : {'isbn' : isbn},
            async : false,
            // cache : false,
            url : findBookByIsbn,
            success : function(data) {
                return flag = data.msg==="true"?true:false
            }
        });
        return flag;
    }
    function checkBookName(name){
        var flag = true;
            $.ajax({
                type : "get",
                dataType : "json",
                data : {'name' : name},
                async : false,
                // cache : false,
                url : findBookByName,
                success : function(data) {
                    return flag = data.msg==="true"?true:false
                }
            });
        return flag;
    }

    function myValidate(){
        $("#submitForm").validate({
            onkeyup: false,
            focusCleanup: false,
            rules: {
                name: {
                    required: true,
                    verifyName: true
                },
                isbn: {
                    required: true,
                    verifyIsbn: true
                },
                price: {
                    required: true,
                    verifyPrice: true
                },
                authorId:{
                    required: true,
                    verifyAuthorId: true
                },
                pbhouseId:{
                    required: true,
                    verifyPbhouseId: true
                }
            },
            messages: {
                name: "已经存在书籍或输入规则有误",
                isbn: "已经存在或输入规则有误",
                price: "请输入最高5位的图书价格",
                authorId: "请输入正确的作者id",
                pbhouseId: "请输入正确的出版社id",
            },
            submitHandler: function(form) {

            }
        })
    }
    $.extend( $.validator.messages, {
        required: "必填字段",
        remote: "请修正此字段",
        email: "请输入有效的电子邮件",
        url: "请输入有效的网址",
        date: "请输入有效的日期",
        dateISO: "请输入有效的日期 (YYYY-MM-DD)",
        number: "请输入有效的数字",
        digits: "只能输入数字",
        creditcard: "请输入有效的信用卡号码",
        equalTo: "你的输入不相同",
        extension: "请输入有效的后缀",
        maxlength: $.validator.format("最多可以输入 {4} 个字符"),
        minlength: $.validator.format("最少要输入 {0} 个字符"),
        rangelength: $.validator.format("请输入长度在 {0} 到 {1} 之间的字符串"),
        range: $.validator.format("请输入范围在 {0} 到 {1} 之间的数值"),
        max: $.validator.format("请输入不大于 {0} 的数值"),
        min: $.validator.format("请输入不小于 {0} 的数值")
    });
    //搜索框
    $("#searchBookNameAndIsbn").blur(function(){
        $("#bookNameList").css('display', 'none')
    });
    $("#searchBookNameAndIsbn").focus(function(){
        $("#bookNameList").css('display', 'block')
    });
    $("#bookNameList").css('display', 'none')
    function catchName(word) {
            word = word.replace(/[^\u4e00-\u9fa5/A-Za-z/0-9]/g, "");
            $("#bookNameList option").remove();
            $("#bookNameList").css('display', 'none')
            $("#bookNameList").css('position', 'relative')
            if (word !== '') {
                $.ajax({
                    type: "get",
                    dataType: "json",
                    data: {'name': word},
                    async: false,
                    // cache : false,
                    url: findBookNameUrl,
                    success: function (data) {
                        var html = "";
                        html = "<option style='font-weight: bolder'>" + "你可能要查询" + "</option>" +

                        $("#bookNameList").append(html);
                        for (var i in data) {
                            html = "<option value='" + data[i] + "' id='" + i + "'>" + data[i] + "</option>";

                            $("#bookNameList").css("display", 'block')
                            $("#bookNameList").append(html);
                        }

                    }

                });

            }
    }
    $('#searchBookNameAndIsbn').focus()
    //404图片
    function imgError(img){
        img.setAttribute("src", img404)
    }
    function bathDelete() {
        var ids = [];
        $("#main input:checked").each(function(i) {
            if ($(this).val() != '') {
                ids.push($(this).val());
            }
        });
        if (ids.length == 0) {
            layer.msg("至少选择一行进行操作!");
            return;
        }
        deletePlat(ids.join(","));

    };

    function deletePlat(ids) {
        layer.confirm('你真的要删除勾选的行?', function(index) {
            layer.load();
            layer.close(index);
            $.ajax({
                url : deleteBookUrl,
                type : 'get',
                datatype : 'json',
                data : {
                    "ids" : ids
                },
                success : function(result) {
                    if (result.code==200) {
                        layer.msg(result.msg);
                        searchData();
                    } else {
                        layer.msg(result.msg);
                    }
                }
            });
        });
    }
    function searchData() {
        dataTable.ajax.reload(null, false);
    };

    /**
     * 清空表单信息
     */
    function clearFrom() {
        $('#submitForm')[0].reset();
        $("input").removeClass("error");
        $("label.error").remove();
    };

    /**
     * 编辑
     * @param id
     */
    function edit(id) {
        clearFrom();
        var form = $("#submitForm");
        //设置表单提交 地址
        form.attr("action", updateBookUrl);
        $.ajax({
            url : editUrl,
            type : 'get',
            datatype : 'json',
            data : {
                "id" : id
            },
            success : function(result) {
                layer.closeAll();
                $('#formShow').show();
                layer.open({
                    title : '修改',
                    type : 1,
                    area : [ '80%', '60%' ], //宽高s
                    content : $('#formShow')
                });
                //填充表单信息
                for ( var d in result) {
                    var $obj = $("#" + d);
                    if ($obj.length > 0) {
                        var tagName = $obj[0].tagName;
                        if (tagName == "IMG") {
                            $obj.attr("src", "" + result[d] + "");
                        } else {
                            $obj.val(result[d] + "");
                        }
                    }
                }
                //验证器
                checkBookNameTel(result)
                checkBookIsbnTel(result)
            }
        });
    };

    /**
     * 提交表单
     */
    function submitFrom() {
        var  flag = true
        var submitForm = $("#submitForm .input-text");
        for (let i = 0; i < submitForm.length; i++) {
            if(submitForm[i].value.trim()===""){
                if (submitForm[i].className.indexOf('url')===-1){
                    submitForm[i].classList.add("error")
                }
            }
            if (submitForm[i].className.indexOf('error')!==-1){
                flag = false
            }
        }
        if (flag===true){
            var form = $("#submitForm");
            layer.load();
            var options = {
                type : 'post',
                success : function(data) {
                    layer.closeAll();
                    if (data.code==200) {
                        searchData();
                    } else {
                        layer.msg(data.msg);
                    }
                }
            };
            form.ajaxSubmit(options);
        }else {
            layer.msg("添加失败")
        }
    };

      $("#submitForm").validate({
          rules : {
              name: {
                  required: true,
                  verifyName: true
              },
          },
          onkeyup : false,
          focusCleanup : true,
          success : "valid",
          submitHandler : function(form) {
              var index = parent.layer.getFrameIndex(window.name);
              parent.layer.close(index);
              submitFrom();
          }
      });


    function add() {
        clearFrom();
        var form = $("#submitForm");
        form.attr("action", addUrl);
        $('#formShow').show();
        layer.open({
            title : '添加',
            type : 1,
            area : [ '80%', '60%' ], //宽高s
            content : $('#formShow'),

        });
    };

</script>
</body>
</html>